package util;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.naming.InitialContext;

import dao.UserDAO;

@FacesValidator("loginValidator")
public class LoginValidator implements Validator {

	@Override
	public void validate(FacesContext context, UIComponent component, Object value)
			throws ValidatorException {		
		if((String.valueOf(component.getAttributes().get("editMode"))).equals("true"))
			return;
		String name = (String) value;
		UserDAO userDAO = null;
		try {
			InitialContext ctx = new InitialContext();
			userDAO = (UserDAO) ctx.lookup("java:global/PaidClinic/JPAUserDAO!dao.UserDAO");
		} catch (Exception e) {
			e.printStackTrace();
		}		
		if(userDAO.selectUserByName(name) != null)
			throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Login already exists", "Login already exists"));
	}
	
}